import time
from Sudoku.Png2 import Png2
from Sudoku.SudokuSolver import SudokuSolver
from Sudoku.TwoArray import TwoArray
from Auto.coordinate import Coordinate
from Auto.adb_click import ADB

# 初始化 ADB 对象
adb_ = ADB()


def process_arrays(A, B, C, blue_, time_sleep):
    """
    遍历 A 数组，如果值为 0 就获取 B 数组的值并点击 C 数组的坐标
    :param A: 初始数独数组
    :param B: 解决后的数独数组
    :param C: 坐标数组
    :param blue_: 底部答案按钮的坐标
    :param time_sleep: 点击间隔时间
    """
    for i in range(len(A)):
        for j in range(len(A[i])):
            if A[i][j] == 0:
                b_value = B[i][j]  # 获取 B 数组对应位置的值
                c_x, c_y = C[i][j]  # 获取 C 数组对应的坐标
                print(f"Value in A is 0 at ({i}, {j}), using B's value {b_value}, clicking at ({c_x}, {c_y})")
                # 点击空格，阶段性成果，因为点满一个格子后有暴击特效，阻碍点击
                # 点击 6 次以上可以有效提高点击成功的概率
                for _ in range(8):
                    adb_.click(c_x, c_y)
                time.sleep(time_sleep)
                # 点击答案
                process_b_value(b_value, blue_)


def process_b_value(b_value, blue_):
    """
    点击答案按钮 1-9
    :param b_value: 需要点击的数字
    :param blue_: 底部答案按钮的坐标
    """
    if 1 <= b_value <= 9:
        index = b_value - 1  # 找到对应的索引
        c_x, c_y = blue_[index]  # 获取对应的坐标
        print(f"b_value is {b_value}, clicking at ({c_x}, {c_y})")
        adb_.click(c_x, c_y)
    else:
        print(f"Invalid b_value: {b_value}")


# TODO: 图像尺寸和设备分辨率限制：565x1004，暂未做等比例计算坐标
# TODO: 截图时点到有数字的空格，会影响到该格识别准确性
# TODO: 空格输入失败时，增加点击次数：for _ in range(7):
if __name__ == '__main__':
    # 初始化 Png2 对象
    png_ = Png2(tesseract_path=r'tesseract.exe')
    adb_.take_screenshot()
    # 传入图片，识别图片中的数字，返回一维列表
    image_path = r"png.jpg"  # 替换为你的图像路径
    digits = png_.solve_sudoku(image_path)
    print("初始一维数组: ", digits)

    # 一维列表转为二维列表
    sudoku_grid = TwoArray.reshape_to_2d_grid(digits)
    sudoku_grid_ = TwoArray.reshape_to_2d_grid(digits)
    print("初始二维数组: ", sudoku_grid_)

    # 解题
    solver = SudokuSolver(sudoku_grid_)
    print("初始数独: ")
    solver.print_grid()

    solved_grid = solver.solve()  # 获取解决后的数独
    if solved_grid:
        print("解决后的数独: ")
        solver.print_grid()
    else:
        print("\n无解,大概率是识别错误,运行前,不要选中有数字的格子")
        exit(0)

    # 获取坐标
    extractor = Coordinate()
    # red_, blue_ 为调试时画在图上的点，81 个红点和 9 个蓝点
    red_, blue_ = extractor.process_image(image_path)
    print(f"初始数组: {sudoku_grid}")
    print(f"解题后的数组: {solved_grid}")
    print(f"81个点击坐标: {red_}")
    print(f"9个底部答案坐标: {blue_}")

    time.sleep(2)
    # 执行点击
    process_arrays(sudoku_grid, solved_grid, red_, blue_, time_sleep=0)



